#!/home/cs1010/anaconda3/envs/mqtt_admin/bin/python

import configparser
import requests
import subprocess
import json


class VolcengineWrapper:
    def __init__(self):
        self.rtc_app_id = self.read_rtc_app_id()
        # voicchat 是否已经启动
        self.is_started = False
        # 设备 ID
        self.device_id = None
        # 房间 ID
        self.room_id = None
        # 用户 ID
        self.uid = None
        # 用户 Token
        self.token = None
        

    def set_device_id(self, device_id):
        # 这里只是示例，实际中需要根据具体逻辑获取设备 ID
        self.device_id = device_id

    def get_device_id(self):
        if self.device_id is None:
            self.device_id = self.read_device_id()
        return self.device_id
    
    def get_is_started(self):
        return self.is_started
    
    def get_app_id(self):
        return self.rtc_app_id
    
    def get_room_id(self):
        if self.room_id is not None:
            return self.room_id
        
    def get_uid(self):
        if self.uid is not None:
            return self.uid
    
    def get_token(self):
        if self.token is not None:
            return self.token

    def read_rtc_app_id(self):
        config = configparser.ConfigParser()
        try:
            config.read('Volcengine/rtc_config.ini')
            return config.get('rtc_config', 'RTC_APP_ID')
        except (configparser.NoSectionError, configparser.NoOptionError):
            print("读取 RTC_APP_ID 时出错，请检查配置文件。")
            return None

    def start_voice_chat(self):
        if self.rtc_app_id is None:
            return None
        authorization = f"af78e30{self.rtc_app_id}"
        headers = {
            'Content-Type': 'application/json',
            'Authorization': authorization
        }
        try:
            response = requests.post('http://127.0.0.1:8080/startvoicechat', headers=headers, json={}, timeout=1)
            response.raise_for_status()
            json_data = response.json()
            if json_data.get('code') == 200:
                print("Start Voice Chat Success ")
                self.room_id = json_data.get('data', {}).get('room_id')
                self.uid = json_data.get('data', {}).get('uid')
                self.token = json_data.get('data', {}).get('token')
                self.is_started = True
            print(json.dumps(json_data, indent=2))
            return json_data
        except requests.RequestException as e:
            print(f"执行请求时出错: {e}")
            return None
        except json.JSONDecodeError:
            print("解析返回的 JSON 信息时出错。")
            return None

    def stop_voice_chat(self):
        if self.is_started:
            self.is_started = False
            authorization = f"af78e30{self.rtc_app_id}"
            headers = {
                'Content-Type': 'application/json',
                'Authorization': authorization
            }
            url = 'http://127.0.0.1:8080/stopvoicechat'
            data = {
                "app_id": self.rtc_app_id,
                "room_id": self.room_id,
                "uid": self.uid
            }
            try:
                response = requests.post(url, headers=headers, json=data)
                response.raise_for_status()
                json_data = response.json()
                if json_data.get('code') == 200:
                    print("Stop Voice Chat Success ")
                # print(json.dumps(json_data, indent=2))
                return json_data
            except requests.exceptions.HTTPError as http_err:
                print(f"HTTP error occurred: {http_err}")
            except requests.exceptions.RequestException as req_err:
                print(f"Request error occurred: {req_err}")
            except ValueError as json_err:
                print(f"JSON decoding error occurred: {json_err}")
            return None


if __name__ == "__main__":
    wrapper = VolcengineWrapper()
    response = wrapper.start_voice_chat()
    if response:
        print("语音聊天启动响应:", response)
    